<template>
  <div class="user">
      <Breadcard name1="用户管理" name2="用户列表" style="margin-bottom:15px"/>
      <el-card class="box-card">
          <el-row :gutter="20">
            <el-col :span="7">
            <!-- 搜索与添加区域 -->
            <el-input placeholder="请输入内容" clearable v-model="queryInfo.query" @clear="getUserList">
                <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
            </el-col>
            <el-col :span="4">
            <!-- 添加用户区域 -->
            <el-button type="primary" @click="DialogVisible = true">用户添加</el-button>
            </el-col>
        </el-row>
        <!-- 用户列表 -->
      <el-table :data="userList" stripe style="width: 100%" border>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="userStatuChanged(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRoles(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        
      </el-table>  
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1,2,5,10]"
        :page-size="queryInfo.pagesize"
        layout="total,sizes, prev, pager, next,jumper"
        :total="total">
        </el-pagination>
      </el-card>
      <!--添加用户对话框-->
      <el-dialog
        @close="addDialogclose"
        title="添加用户"
        :visible.sync="DialogVisible"
        width="50%">
        <el-form :model="addForm" status-icon :rules="addFormrules" ref="addFormRef" label-width="70px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="DialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
        </el-dialog>
        <el-dialog
          title="编辑用户"
          :visible.sync="editDialogVisible"
          width="50%">
          <el-form :model="editForm" status-icon :rules="addFormrules" ref="editFormRef" label-width="70px" class="demo-ruleForm">
            <el-form-item label="用户名" >
              <el-input v-model="editForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" >
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" >
              <el-input v-model="editForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUserinfo">确 定</el-button>
          </span>
        </el-dialog>
        <el-dialog
          title="分配角色"
          @close="clearRoledialog"
          :visible.sync="RoledialogVisible"
          width="50%">
          <div>
            <p>当前的用户：{{userinfo.username}}</p>
            <p>当前的角色：{{userinfo.role_name}}</p>
            <p>分配新角色：
              <el-select v-model="selectedRoleId" placeholder="请选择">
                <el-option
                  v-for="item in rolesList"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id">
                </el-option>
              </el-select>
            </p>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="RoledialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveroleInfo">确 定</el-button>
          </span>
        </el-dialog>      
  </div>
</template>

<script>
import Breadcard from '../Breadcard/Breadcard.vue'
export default {
    name:'Users',
    components:{
        Breadcard
    },
    data () {
      //验证邮箱的规则
      var checkEmail = (rule,value,callback) => {
        const regEmail = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
        if(regEmail.test(value)){
          return callback()
        }
        callback(new Error('请输入合法的邮箱'))
      }
      var checkMobile = (rule,value,callback) => {
        const regMobile = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/
        if(regMobile.test(value)){
          return callback()
        }
        callback(new Error('请输入合法的手机号'))
      }
        
        return {
            // 获取用户列表的参数对象
            queryInfo: {
                // 搜索值
                query: '',
                // 当前的页数
                pagenum: 1,
                // 当前每次显示多少条数据
                pagesize: 5
            },
            userList:[],
            total:0,
            //控制添加用户对话框的现实与隐藏
            DialogVisible:false,
            //控制编辑对话框显隐
            editDialogVisible:false,
            //控制分配角色对话框显隐
            RoledialogVisible : false,
            //添加用户的表单数据
            addForm:{
              username:'',
              password:'',
              email:'',
              mobile:'',
            },
            //获取查询数据
            editForm:{},
            //添加表单验证规则
            addFormrules:{
              username:[
                {required:true,message:'请输入用户名',trigger:'blur'},
                {min:3,max:10,message:'用户名的长度在3-10个字符之间',trigger:'blur'}
              ],
              password:[
                {required:true,message:'请输入密码',trigger:'blur'},
                {min:6,max:15,message:'用户名的长度在6-15个字符之间',trigger:'blur'}
              ],
              email:[
                {required:true,message:'请输入邮箱',trigger:'blur'},
                {validator:checkEmail,trigger:'blur'}
              ],
              mobile:[
                {required:true,message:'请输入手机号',trigger:'blur'},
                {validator:checkMobile,trigger:'blur'}
              ]
            },
            //需要被分配角色的用户的信息
            userinfo:[],
            //所有角色的数据列表
            rolesList:[],
            //被选中的用户的id
            selectedRoleId:''
            
        }
    },
    created(){
        this.getUserList()
    },
    methods:{
        //获取用户列表
        async getUserList(){
            const {data:res} = await this.$http.get('users',{params:this.queryInfo})
            if(res.meta.status !== 200){
                return this.$message.error('获取用户列表失败')
            }
            this.$message.success('获取用户列表成功!')
            this.userList = res.data.users
            this.total = res.data.total
            console.log(res)
        },
        addDialogVisible(){
            
        },
        //监听状态的变化
        async userStatuChanged(userinfo){
            console.log(userinfo)
            const {data:res} = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
            if(res.meta.status !== 200){
                userinfo.mg_state = !userinfo.mg_state
                return this.$message.error('更新用户信息失败')
            }
            this.$message.success('更新用户信息成功')

        },
        async showEditDialog(id){
          const {data:res} = await this.$http.get('users/' + id)
          if(res.meta.status !== 200){
            return this.$message.error('查询用户失败')
          }
          this.$message.success('查询用户成功')
          this.editForm = res.data
          this.editDialogVisible = true
        },
        // 根据id删除对应的用户信息
        async removeUserById(id) {
          // 询问用户是否删除用户
          const confirmRusult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '永久删除该用户', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err)
          console.log(confirmRusult)
          // 用户点击了删除,则返回字符串 confirm
          // 用户取消了删除,则返回字符串 cancel
          if (confirmRusult !== 'confirm') {
            return this.$message.info('已经取消了删除')
          }
          this.$http.delete('users/' + id).then(res => {
            const { data: response } = res
            console.log(response)
            if (response.meta.status !== 200) {
              return this.$message.error('该用户删除失败')
            }
            this.$message.success('该用户已经删除')
            this.getUserList()
          })
        },
        // 监听 pagesize 改变事件 每页显示的个数
        handleSizeChange(newPage){
            this.queryInfo.pagesize = newPage
            this.getUserList()
        },
        // 监听 页码值 改变的事件 当前页面值
        handleCurrentChange(newPage){
            this.queryInfo.pagenum = newPage
            this.getUserList()
        },
        addDialogclose(){
          this.$refs.addFormRef.resetFields()
        },
        //添加用户
        addUser(){
          this.$refs.addFormRef.validate(async valid => {
            if(!valid) return Error()
            const {data:res} = await this.$http.post('users',this.addForm)
            if(res.meta.status !== 200){
              return this.$message.error('用户添加失败')
            }
            this.$message.success('用户添加成功')
            this.DialogVisible = false
            this.getUserList()
          })
        },
        //编辑用户信息
        editUserinfo(){
          this.$refs.editFormRef.validate(async valid => {
            if(!valid) return Error()
            const {data:res} = await this.$http.put('users/' + this.editForm.roleId,
            {
              email:this.editForm.email,
              mobile:this.editForm.mobile
            })
            if(res.meta.status !== 200){
              return this.$message.error('更新用户信息失败')
            }
            this.editDialogVisible = false
            this.getUserList()
            this.$message.success('更新用户信息成功')
          })
        },
        //分配角色按钮
        async setRoles(userinfo){
          this.userinfo = userinfo
          //在展示对话框之前获取所有角色信息
          const {data:res} = await this.$http.get('roles')
          if(res.meta.status !== 200){
            return this.$message.error('获取角色信息失败')
          }
          this.rolesList = res.data
          this.RoledialogVisible = true
        },
        async saveroleInfo(){
          if(!this.selectedRoleId){
            return this.$message.error('请选择要分配的角色')
          }
          const {data:res} = await this.$http.put(`users/${this.userinfo.id}/role`,{
            rid:this.selectedRoleId
          })
          if(res.meta.status !== 200){
            return this.$message.error('更新角色失败')
          }
          this.$message.success('更新角色成功')
          this.getUserList()
          this.RoledialogVisible = false
        },
        clearRoledialog(){
          this.selectedRoleId = ''
          this.userinfo = []
        }
    }

}
</script>

<style lang="less" scoped>
.el-card{
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15);
    .el-pagination{
    float: right;
    margin-top: 15px;
}
}

</style>